package com.servlet.listener;

import com.servlet.bean.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

/**
 * @Title: MySessionListener
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/26 15:30
 */
@WebListener
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        User user = (User) session.getAttribute("user");
        ServletContext servletContext = session.getServletContext();
        List<User> list = ( List<User>)servletContext.getAttribute("online");
        if(list.contains(user)) {
            list.remove(user);
        }

    }
}
